const uuid = require('uuid');
const fs = require('fs');
const path = require('path');
const tool = require('../tool');

/**
 * 覆盖文件内容
 *
 * @param {String} filePath
 * @param {Object} content
 * @return {Promise} 
 */
function coverFile(filePath, content) {
    return new Promise((resolve, reject) => {
        try {
            fs.writeFile(filePath, content, (e) => {
                if (e) {
                    reject();
                }
                resolve();
            });
        } catch {
            reject();
        }
    });
}
/**
 * 从文件中读取所有用户信息
 *
 * @return {Object} 
 */
function getUser() {
    return new Promise((resolve, reject) => {
        fs.readFile(path.join(__dirname, '../data/user.json'), (err, data) => {
            if (err) {
                reject(err);
            }
            resolve(JSON.parse(data));
        });
    })
}
/**
 * 将用户信息写入文件
 *
 * @param {Object} content
 */
function setUser(content) {
    coverFile(path.join(__dirname, '../data/user.json'), JSON.stringify(content)).then(() => true).catch(() => false);
}

const userFileData = {};

let _this;
const user = _this = {

    /**
     * 登录验证
     * TODO 需要从数据库拉取用户信息和储存sid
     *
     * @param {Object} data 包含用户名和密码
     * @param {Object} sid 请求头的sid信息
     * @return {Promise} 
     */
    login: (data, sid) => {
        if (data.signin) {

            return new Promise((resolve, reject) => {
                getUser().then((users) => {
                    const sid = uuid.v4();

                    let name = 'visitor-' + uuid.v4();

                    users[name] = {
                        loginStatus: true,
                        sid: sid,
                        password: '',
                    }
                    setUser(users);

                    resolve({
                        name: name,
                        loginStatus: true,
                        sid: sid,
                    });
                }).catch(result => console.log(result));
            });
        } else {
            return new Promise((resolve, reject) => {
                getUser().then((user) => {
                    // 没有存储信息的情况
                    if (!user[data.name]) {
                        reject({
                            name: data.name,
                            loginStatus: false
                        });
                    } else {
                        // 使用sid的状况
                        if (sid && sid === user[data.name].sid) {
                            user[data.name].loginStatus = true;
                            setUser(user);
                            resolve({
                                name: data.name,
                                loginStatus: user[data.name].loginStatus,
                            });
                        } else if (data.password === user[data.name].password && !user[data.name].loginStatus) {
                            // 使用用户名和密码的情况，在未登录的情况下才能登录
                            user[data.name].loginStatus = true;
                            user[data.name].sid = uuid.v4();;
                            setUser(user);
                            resolve({
                                name: data.name,
                                loginStatus: user[data.name].loginStatus,
                                sid: user[data.name].sid,
                            });
                        } else {
                            // 没有一样匹配的情况
                            reject({
                                name: data.name,
                                loginStatus: false
                            });
                        }
                    }
                }).catch(result => console.log(result));

            });
        }
    },
    logout: function (userName, flag) {
        getUser().then((user) => {
            const usr = user[userName];

            if (usr) {
                if (flag) {
                    usr.sid = '';
                }
                usr.loginStatus = false;
                console.log(`[${userName}]已退出登录！`);
                setUser(user);
            }
        }).catch();
    },
    status: function (userName, callback) {
        let status = false;
        getUser().then((user) => {
            if (user[userName]) {
                status = user[userName].loginStatus;
            }
            callback && callback(status);
        });
    },
    hasApp: function (userName, projectName, callback) {
        const userPath = path.join(__dirname, `../user/user_${userName}/app.json`);

        fs.readFile(userPath, (err, data) => {
            if (err) {
                throw new Error(err);
            }
            const apps = JSON.parse(data);

            try {
                for (let id in apps) {
                    if (apps[id] === projectName) {
                        callback && callback(true);
                        throw new Error(); // 跳出循环
                    }
                }
                callback && callback(false);
            } catch { }
        });
    },
    addApp(userName, projectName, callback) {
        const userPath = path.join(__dirname, `../user/user_${userName}/app.json`);
        fs.readFile(path.join(__dirname, '../data/app-repo.json'), (err, data) => {
            if (err) {
                throw new Error(err);
            }

            const repo = JSON.parse(data);
            let app = null;
            for (let id in repo) {
                if (repo[id].projectName === projectName) {
                    app = repo[id];
                    break;
                }
            }
            fs.readFile(userPath, (err, data) => {
                if (err) {
                    throw new Error(err);
                }
                const userApp = JSON.parse(data);
                // 寻找空位插入app
                let id = null;
                for (let i = 0; i < 170; i++) {
                    if (!userApp[tool.addZero(i, 3)]) {
                        userApp[tool.addZero(i, 3)] = app;
                        id = tool.addZero(i, 3);
                        break;
                    }
                }

                fs.writeFile(userPath, JSON.stringify(userApp), () => {
                    callback && callback({ id: id, app: app });
                });
            });

        });
    },
    deleteApp(userName, appId, callback) {
        const userPath = path.join(__dirname, `../user/user_${userName}/app.json`);
        fs.readFile(userPath, (err, data) => {
            if (err) {
                throw new Error(err);
            }
            const userApp = JSON.parse(data);
            if (userApp[appId].projectName !== 'AppStore') {
                delete userApp[appId];
                fs.writeFile(userPath, JSON.stringify(userApp), () => {
                    callback && callback();
                });
            } else {
                callback && callback();
            }
        });
    },
    addFile(userName, fileInfo, fileType, callback) {
        const userPath = path.join(__dirname, `../user/user_${userName}/app.json`);
        const defaultPath = path.join(__dirname, `../data/app-default.json`);

        // 如果有缓存，说明是重复文件写入，直接返回
        if (userFileData[fileInfo.name] === fileType) {
            return;
        }

        const file = {
            "icon": fileInfo.icon,
            "cover": "",
            "description": "",
            "name": fileInfo.name,
            "projectName": fileInfo.execApp,
            "size": {
                "width": 65,
                "height": 65
            },
            "url": fileInfo.url,
            "cache": {},
            "onTaskBar": false,
            "maxable": true,
            "type": "file"
        }

        // 直接将文件信息写入
        fs.readFile(userPath, (err, data) => {
            // 如果用户信息读不到就找默认信息，然后添加内容，写入文件
            if (err) {
                fs.readFile(defaultPath, (err, data) => {
                    if (err) throw err;
                    addToFile(userPath, data, file, fileInfo, fileType, callback);
                })
            } else {
                addToFile(userPath, data, file, fileInfo, fileType, callback);
            }
        });
    },
    removeVisitor(users, userName, callback) {
        // 删除文件
        fs.rm(path.join(__dirname, `../user/user_${userName}`), { force: true, recursive: true }, callback);
        // 删除user.json记录
        delete users[userName];
    },
    removeAllVisitors() {

        getUser().then((users) => {
            for (let userName in users) {
                if (userName.indexOf('visitor-') === 0 && userName.length === 44) {
                    // 用户不在线时删除记录
                    if (!users[userName]['loginStatus']) {
                        this.removeVisitor(users, userName, () => {});
                    }
                }
            }
            setUser(users);
        }).catch(console.error);
    }
}

function addToFile(userPath, data, file, fileInfo, fileType, callback) {
    const userApp = JSON.parse(data);

    for (let id in userApp) {
        if (userApp[id].name === fileInfo.name) {
            userFileData[fileInfo.name] = fileType;
            return;
        }
    }

    // 寻找空位插入app
    let id = null;
    for (let i = 0; i < 170; i++) {
        if (!userApp[tool.addZero(i, 3)]) {
            userApp[tool.addZero(i, 3)] = file;
            id = tool.addZero(i, 3);
            break;
        }
    }

    fs.writeFile(userPath, JSON.stringify(userApp), () => {
        callback && callback({ id: id, app: file });
    });
}

module.exports = user;
